<!-- eslint-disable vue/no-parsing-error -->
<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input v-model="params.name" clearable placeholder="请输入内容" class="search-main" />
      <el-button type="primary" @click="serchFn">查询</el-button>
    </div>
    <div class="create-container">
      <el-button v-auth="'park:enterprise:add_edit'" type="primary" @click="$router.push('/enterpriseAdd')">
        添加企业
      </el-button>
      <el-button type="primary" @click="exportFn">导出excel</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="exterpriseList" @expand-change="expandChange">
        <el-table-column type="expand">
          <template #default="{row}">
            <!-- props是当前这一行的数据 -->
            <!-- props.row是修改数据不是新增数据 -->
            <el-table :data="row.rentData">
              <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
              <el-table-column label="租赁起始时间" prop="startTime" />
              <el-table-column label="合同状态" prop="status">
                <template #default="prop">
                  <el-tag :type="formatInfoType(prop.row.status)">
                    {{ formartStatus(prop.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="scope">
                  <el-button
                    size="mini"
                    type="text"
                    :disabled="scope.row.renewFlag===0"
                    @click="xuZu(scope.row,row.id)"
                  >续租</el-button>

                  <el-button
                    size="mini"
                    type="text"
                    :disabled="scope.row.status===1||scope.row.exitFlag===0"
                    @click="tuiZu(scope.row.id)"
                  >退租</el-button>

                  <el-button
                    size="mini"
                    type="text"
                    :disabled="scope.row.status===0||scope.row.status===1"
                    @click="delHeTo(scope.row.id) "
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column
          label="联系电话"
          prop="contactNumber"
        />
        <el-table-column label="操作">
          <!-- #default="scope" -->
          <template #default="{row}">
            <el-button size="mini" type="text" @click="addRent(row.id)">添加合同</el-button>
            <el-button size="mini" type="text" @click="$router.push('/exterpriseDetail?id='+row.id)">查看</el-button>
            <el-button size="mini" type="text" @click="editFn(row.id)">编辑</el-button>
            <el-button size="mini" type="text" @click="delFn(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        layout="total, prev, pager, next,sizes"
        :page-sizes="[2, 4, 6, 8]"
        :total="total"
        :page-size="params.pageSize"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>

    <el-dialog
      :title="title=='添加合同' ? '添加合同' : '续租合同'"
      :visible.sync="rentDialogVisible"
      width="580px"
      @close="closeDialog"
    >
      <!-- 表单区域 -->
      <div class="form-container">
        <!-- 表单模版 -->
        <el-form ref="addForm" :model="rentForm" :rules="rentRules" label-position="top">
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" placeholder="请选择" :disabled="jinYong">
              <el-option
                v-for="item in buildingList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="rentTime">
            <el-date-picker
              v-model="rentForm.rentTime"
              type="daterange"
              range-separator="至"
              :start-placeholder="title==='添加合同' ? '开始日期 ' : rentForm.rentTime[0]"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions"
            />
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <!-- :before-upload="beforeUpload"上传前的校验 -->
            <el-upload
              action="#"
              :file-list="fileList"
              :http-request="uploadRequest"
              :before-upload="beforeUpload"
            >
              <el-button size="small" type="primary" plain>上传合同文件</el-button>
              <div slot="tip" class="el-upload__tip">支持扩展名：.doc .docx .pdf, 文件大小不超过5M</div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button size="mini" @click="closeDialog">取 消</el-button>
        <el-button size="mini" type="primary" @click="addFn">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { utils, writeFileXLSX } from 'xlsx'
import { delExterpriseAPI,
  getEnterpriseList,
  getRentBuildListAPI,
  uploadAPI,
  createRentAPI,
  getRentListAPI,
  delHeAPI,
  delTuiAPI } from '@/api/enterprise'
export default {
  name: 'Building',
  data() {
    return {
      title: '添加合同',
      jinYong: false,
      buildId: null,
      exterpriseList: [],
      params: {
        page: 1,
        pageSize: 6,
        name: ''
      },
      total: 0,
      rentDialogVisible: false,
      rentForm: {
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: '', // 合同Url
        enterpriseId: null, // 企业名称
        type: 0, // 合同类型
        rentTime: [] // 合同时间
      },
      buildingList: [],
      // 上传的合同列表
      fileList: [],
      rentRules: {
        buildingId: [
          { required: true, message: '请选择楼宇', trigger: 'change' }
        ],
        rentTime: [
          { required: true, message: '请选择租赁日期', trigger: 'change' }
        ],
        contractId: [
          { required: true, message: '请上传合同文件' }
        ]
      },
      // 禁用之前的时间
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() <= Date.now()
        }
      }
    }
  },
  created() {
    this.getExterpriseList()
  },
  methods: {
    async getExterpriseList() {
      const res = await getEnterpriseList(this.params)
      // console.log(res)
      const newData = res.data.rows.map(item => {
        return {
          ...item,
          rentData: []
        }
      })
      this.exterpriseList = newData
      this.total = res.data.total
    },
    // 表格行展开收起事件
    async expandChange(row, rows) {
      // row是当前展开的
      // rows是已经展开了那些
      // console.log(rows)
      const res = await getRentListAPI(row.id)
      // console.log(res)
      // 不是新增一个rentData数据，而是修改原有的rentData属性
      // eslint-disable-next-line require-atomic-updates
      row.rentData = res.data
    },
    // 分页器页码
    handleCurrentChange(val) {
      // console.log(val)
      // 更改参数
      this.params.page = val
      // 重新获取数据渲染
      this.getExterpriseList()
    },
    handleSizeChange(val) {
      // console.log(val)
      this.params.pageSize = val
      this.getExterpriseList()
    },
    // 查询
    serchFn() {
      this.params.page = 1
      this.getExterpriseList()
    },
    // 删除
    delFn(id) {
      // console.log(id)
      this.$confirm('确认删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await delExterpriseAPI(id)
        if (res.code !== 10000) {
          this.$message.error('删除失败，' + res.msg)
        } else {
          this.$message.success('删除成功')
          this.getExterpriseList()
        }
      })
    },
    // 传递id
    editFn(id) {
      this.$router.push({
        path: '/enterpriseAdd',
        query: {
          id
        }
      })
    },
    // 上传文件校验
    beforeUpload(file) {
      // console.log(file)
      const fileType = [
        'application/msword',
        'application/pdf',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
      ]
      const max = 5 * 1024 * 1024
      const A = fileType.includes(file.type)
      const B = file.size <= max
      if (!A) {
        this.$message.error('支持扩展名：.doc .docx .pdf!')
        return false
      }
      if (!B) {
        this.$message.error('上传合同大小不能超过 5MB!')
        return false
      }
      return A && B
    },
    // 上传文件
    async uploadRequest(data) {
      // console.log(data.file)
      const formData = new FormData()
      formData.append('file', data.file)
      formData.append('type', 'contract')
      // 调接口 formData是要传的数据
      const res = await uploadAPI(formData)
      // console.log(res)
      this.rentForm.contractUrl = res.data.url
      this.rentForm.contractId = res.data.id
      this.$refs.addForm.validate(isOK => {
        console.log(isOK)
      })
    },
    // async uploadRequest(data) {
    //   const formData = new FormData()
    //   formData.append('file', data.file)
    //   formData.append('type', 'contract')
    //   const res = await uploadAPI(formData)
    //   console.log(res)
    //   this.rentForm.contractUrl = res.data.url
    //   this.rentForm.contractId = res.data.id
    //   this.$refs.addForm.validate(isOK => {
    //     console.log(isOK)
    //   })
    // },
    // 打开
    async addRent(id) {
      this.title = '添加合同'
      this.rentDialogVisible = true
      this.jinYong = false
      const res = await getRentBuildListAPI()
      // console.log(res)
      this.buildingList = res.data
      // 把企业id存入表单对象
      this.rentForm.enterpriseId = id
    },
    // 关闭
    closeDialog() {
      this.rentDialogVisible = false
      // 重置表单
      this.$refs.addForm.resetFields()
      this.fileList = []
    },
    // 添加企业的提交
    addFn() {
      this.$refs.addForm.validate(async isOK => {
        if (isOK) {
          if (this.title === '添加合同') {
            const { buildingId, contractId, contractUrl, enterpriseId, type } = this.rentForm
            await createRentAPI({
              buildingId, contractId, contractUrl, enterpriseId, type,
              startTime: this.rentForm.rentTime[0],
              endTime: this.rentForm.rentTime[1]
            }).then(res => {
              if (res.code !== 10000) {
                this.$message.error('添加失败，' + res.msg)
              } else {
                this.$message.success('添加成功')
                this.rentDialogVisible = false
                this.getExterpriseList()
              }
            })
          } else {
            await createRentAPI({
              buildingId: this.buildId,
              contractId: this.rentForm.contractId,
              contractUrl: this.rentForm.contractUrl,
              enterpriseId: this.rentForm.enterpriseId,
              type: this.rentForm.type,
              startTime: this.rentForm.rentTime[0],
              endTime: this.rentForm.rentTime[1]
            })
            this.$message.success('修改成功')
            this.getExterpriseList()
            this.rentDialogVisible = false
            this.rentForm = {
              buildingId: null, // 楼宇id
              contractId: null, // 合同id
              contractUrl: '', // 合同Url
              enterpriseId: null, // 企业名称
              type: 0, // 合同类型
              rentTime: [] // 合同时间
            }
          }
        }
      })
    },
    // 格式化tag类型
    formatInfoType(status) {
      const MAP = {
        0: 'warning',
        1: 'success',
        2: 'info',
        3: 'danger'
      }
      // return 格式化之后的中文显示
      return MAP[status]
    },
    // 格式化status
    formartStatus(type) {
      const TYPEMAP = {
        0: '待生效',
        1: '生效中',
        2: '已到期',
        3: '已退租'
      }
      return TYPEMAP[type]
    },
    xuZu(row, id) {
      this.title = '续租合同'
      this.rentDialogVisible = true
      this.jinYong = true
      console.log(row)
      this.rentForm.buildingId = row.buildingName
      this.rentForm.rentTime[0] = row.endTime
      this.rentForm.type = 1
      this.rentForm.enterpriseId = id
      this.buildId = row.buildingId
    },
    delHeTo(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // console.log(id)
        await delHeAPI(id)
        this.$message.success('删除成功')
        this.getExterpriseList()
      })
    },
    tuiZu(id) {
      this.$confirm('此操作将退租, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // console.log(id)
        await delTuiAPI(id)
        this.$message.success('退租成功')
        this.getExterpriseList()
      })
    },
    // 导出excel
    exportFn() {
      // 1、下载xlsx包
      // 2、绑定点击事件，添加导出方法
      // 导出实现：
      // 1、利用utils创建一个新的页签（xlsx文件）
      const file = utils.book_new()
      // 2、还需要sheet页，这才是真正方数据的地方
      // 数据不论多复杂都可以自动转换成sheet
      // 数据的key默认就是表头
      const sheet = utils.json_to_sheet(this.exterpriseList)
      // 把准备好的sheet加入到xslx中
      utils.book_append_sheet(file, sheet, 'sheet的名字')
      // 将准备号的book变为真正的文件
      writeFileXLSX(file, '企业列表.xlsx')
    }
  }
}

</script>

<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container{
  margin: 10px 0px;
}
.page-container{
  padding:4px 0px;
  text-align: right;
}
.form-container{
  padding:0px 80px;
}
</style>
